/*
 * Copyright 2008 Jens Meiss
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package hmvc.j2me.midlet;

import javax.microedition.lcdui.Display;
import javax.microedition.midlet.MIDlet;

import hmvc.j2me.controller.AController;
import hmvc.j2me.events.CloseApplicationEvent;
import hmvc.j2me.events.IEvent;
import hmvc.j2me.events.PauseEvent;
import hmvc.j2me.events.ShowDisplayAbleEvent;
import hmvc.j2me.view.IView;

/**
 * @author jens.meiss
 *
 */
public class HmvcMidletController extends AController implements IHmvcMidlet {
	
	private MIDlet midlet;
	
	private Display display;
	
	private IView viewCurrent;
	
	public HmvcMidletController(MIDlet midlet) {
		setMidlet(midlet);
		setDisplay(Display.getDisplay(midlet));
	}

	public Display getDisplay() {
		return display;
	}

	public MIDlet getMidlet() {
		return midlet;
	}

	public void setDisplay(Display display) {
		this.display = display;
	}

	public void setMidlet(MIDlet midlet) {
		this.midlet = midlet;
	}

	public void init() {
		// TODO Auto-generated method stub
		
	}

	public void terminate() {
		// TODO Auto-generated method stub
		
	}

	public void handleEvent(IEvent event) {
		
		if (event instanceof ShowDisplayAbleEvent) {
			
			if (getViewCurrent() != null) {
				getViewCurrent().setVisible(false);
			}
			
			IView view = (IView) event.getPayload();
			getDisplay().setCurrent(view.getDisplayable());
			view.setVisible(true);
			
			setViewCurrent(view);
			
		} else if (event instanceof CloseApplicationEvent) {
			getMidlet().notifyDestroyed();
		}
	}

	public void registerEvents() {
		getComponent().register(ShowDisplayAbleEvent.class, this);
		getComponent().register(CloseApplicationEvent.class, this);
		getComponent().register(PauseEvent.class, this);
	}

	private IView getViewCurrent() {
		return viewCurrent;
	}

	private void setViewCurrent(IView viewCurrent) {
		this.viewCurrent = viewCurrent;
	}
	
}
